package cn.com.cifi.mars.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.constant.ModuleTypeEunm;
import cn.com.cifi.mars.constant.NoticeAffectedEnum;
import cn.com.cifi.mars.constant.ProcessingModeEnum;
import cn.com.cifi.mars.constant.ProcessingStateEnum;
import cn.com.cifi.mars.constant.VersionStatusEnum;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.entity.MymRooms;
import cn.com.cifi.mars.entity.PriceVersion;
import cn.com.cifi.mars.entity.SysNotice;
import cn.com.cifi.mars.service.MymRoomInfoService;
import cn.com.cifi.mars.service.MymRoomsService;
import cn.com.cifi.mars.service.PriceVersionValueOrgService;
import cn.com.cifi.mars.service.SignPlanVersionService;
import cn.com.cifi.mars.service.SupplyPlanVersionService;
import cn.com.cifi.mars.service.SysNoticeService;
import cn.com.cifi.mars.util.StrUtils;
import cn.com.cifi.mars.util.SynchrolockUtil;
import cn.com.cifi.mars.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class MymRoomInfoServiceImpl implements MymRoomInfoService {

    private static final Logger logger = LoggerFactory.getLogger(MymRoomInfoServiceImpl.class);

    @Autowired
    private MymRoomsService mymRoomsService;

    @Autowired
    private SysNoticeService sysNoticeService;

    @Autowired
    private SupplyPlanVersionService supplyPlanVersionService;

    @Autowired
    private PriceVersionValueOrgService priceVersionValueOrgService;

    @Autowired
    private SignPlanVersionService signPlanVersionService;

    @Autowired
    private DmOdsMyVsMarsSContractServiceImpl dmOdsMyVsMarsSContractServiceImpl;

    @Autowired
    private SynchrolockUtil synchrolockUtil;

    @Autowired
    private PriceVersionServiceImpl priceVersionServiceImpl;

    @Override
    public void updateRooms(String rooms, LocalDateTime now, String instId) {
        Map<String, String> returnMap = new HashMap<String, String>();
        Map<String, String> stageIds = new HashMap<String, String>();
        List<MymRooms> dataList = Collections.synchronizedList(new ArrayList<>());
        try {
            JSONObject roomsObj =  JSON.parseObject(rooms);
            JSONArray roomsArray = roomsObj.getJSONObject("requestInfo").getJSONObject("rooms").getJSONArray("roomsLine");
            if(roomsArray != null && !roomsArray.isEmpty()) {
                String timestampId = UUIDUtils.create();
                for(int i =0; i < roomsArray.size(); i ++ ) {
                    JSONObject  roomObj = roomsArray.getJSONObject(i);
                    String projectFID = roomObj.getString("projectFID");
                    MymRooms room = createRoom(now, timestampId, roomObj, projectFID);
                    dataList.add(room);
                    stageIds.put(projectFID, timestampId);
                }
            }
            mymRoomsService.saveRooms(dataList);
        } catch (Exception e) {
            log.error("###### errorMsg: ", e);
            returnMap.put("returnStatus", "N");
            returnMap.put("returnMsg", "调用失败");
        }

        //刷新货值信息
        Thread refreshPriceVersionByMymRooms = new RefreshPriceVersionByMymRooms(now,instId,stageIds);
        refreshPriceVersionByMymRooms.start();

    }

    /**
      * 设置room信息
     * @return
     */
	private MymRooms createRoom(LocalDateTime now, String timestampId, JSONObject roomObj, String projectFID) {
		MymRooms room = new MymRooms();
		room.setKingdeeProjectID(roomObj.getString("kingdeeProjectID"));
		room.setKingdeeProjectFID(roomObj.getString("kingdeeProjectFID"));
		room.setProjectID(roomObj.getString("projectID"));
		room.setProjectName(roomObj.getString("projectName"));
		room.setProjectFID(projectFID);
		room.setBldPrdId(roomObj.getString("bldPrdID"));
		room.setFormatBuildingCode(roomObj.getString("formatBuildingCode"));
		room.setFormatBuildingName(roomObj.getString("formatBuildingName"));
		room.setProjGUID(roomObj.getString("ProjGUID"));
		room.setBldGUID(roomObj.getString("BldGUID"));
		room.setBldCode(roomObj.getString("BldCode"));
		room.setBldArea(StrUtils.stringToBigDecimal(roomObj.getString("bldArea")));
		room.setRoomGUID(roomObj.getString("roomGUID"));
		room.setUnitNo(StrUtils.stringToInteger(roomObj.getString("unitNo")));
		room.setUnit(roomObj.getString("unit"));
		room.setFloorNo(StrUtils.stringToInteger(roomObj.getString("floorNo")));
		room.setFloorName(roomObj.getString("floorName"));
		room.setRoom(roomObj.getString("room"));
		room.setNo(roomObj.getString("no"));
		room.setRoomNo(StrUtils.stringToInteger(roomObj.getString("roomNo")));
		room.setRoomInfo(roomObj.getString("roomInfo"));
		room.setTotal(StrUtils.stringToBigDecimal(roomObj.getString("total")));
		room.setTnArea(StrUtils.stringToBigDecimal(roomObj.getString("tnArea")));
		room.setTnPrice(StrUtils.stringToBigDecimal(roomObj.getString("tnPrice")));
		room.setOpeningBatch(roomObj.getString("OpeningBatch"));
		room.setHxGUID(roomObj.getString("hxGUID"));
		room.setHxName(roomObj.getString("hxName"));
		room.setJFDate(roomObj.getString("jFDate"));
		room.setBaBldPrice(StrUtils.stringToBigDecimal(roomObj.getString("baBldPrice")));
		room.setBaTnPrice(StrUtils.stringToBigDecimal(roomObj.getString("baTnPrice")));
		room.setDjBldPrice(StrUtils.stringToBigDecimal(roomObj.getString("djBldPrice")));
		room.setDjTnPrice(StrUtils.stringToBigDecimal(roomObj.getString("djTnPrice")));
		room.setDjTotal(StrUtils.stringToBigDecimal(roomObj.getString("djTotal")));
		room.setBaseTotal(StrUtils.stringToBigDecimal(roomObj.getString("baseTotal")));
		room.setBaseTnPrice(StrUtils.stringToBigDecimal(roomObj.getString("baseTnPrice")));
		room.setBaseBldPrice(StrUtils.stringToBigDecimal(roomObj.getString("baseBldPrice")));
		room.setScBldArea(StrUtils.stringToBigDecimal(roomObj.getString("scBldArea")));
		room.setScTnArea(StrUtils.stringToBigDecimal(roomObj.getString("scTnArea")));
		room.setYsBldArea(StrUtils.stringToBigDecimal(roomObj.getString("ysBldArea")));
		room.setYsTnArea(StrUtils.stringToBigDecimal(roomObj.getString("ysTnArea")));
		room.setxIszc(StrUtils.stringToInteger(roomObj.getString("x_IsZc")));
		room.setIsAnnexe(StrUtils.stringToInteger(roomObj.getString("isAnnexe")));
		room.setIsVirtualRoom(StrUtils.stringToInteger(roomObj.getString("isVirtualRoom")));
		room.setIsTradeLock(StrUtils.stringToInteger(roomObj.getString("isTradeLock")));
		room.setCreatedTime(now.toString().replace("T", " "));
		room.setCreatedGUID(roomObj.getString("createdGUID"));
		room.setModifiedTime(roomObj.getString("modifiedTime"));
		room.setModifiedGUID(roomObj.getString("modifiedGUID"));
		room.setVersionNumber(roomObj.getString("versionNumber"));
		room.setStatusEnum(StrUtils.stringToInteger(roomObj.getString("statusEnum")));
		room.setAreaChgGUID(roomObj.getString("areaChgGUID"));
		room.setRoomStru(roomObj.getString("roomStru"));
		room.setIsHfLock(StrUtils.stringToInteger(roomObj.getString("isHfLock")));
		room.setCalModeEnum(StrUtils.stringToInteger(roomObj.getString("calModeEnum")));
		room.setCalMode(roomObj.getString("calMode"));
		room.setAreaStatusEnum(StrUtils.stringToInteger(roomObj.getString("areaStatusEnum")));
		room.setAreaStatus(roomObj.getString("areaStatus"));
		room.setProductTypeGUID(roomObj.getString("productTypeGUID"));
		room.setCreatedName(roomObj.getString("createdName"));
		room.setModifiedName(roomObj.getString("modifiedName"));
		room.setDspAreaStatus(roomObj.getString("dspAreaStatus"));
		room.setStatus(roomObj.getString("status"));
		room.setxRoomcode(roomObj.getString("x_RoomCode"));
		room.setBottomPriceReturnHouseLock(StrUtils.stringToInteger(roomObj.getString("bottomPriceReturnHouseLock")));
		room.setDspBldArea(StrUtils.stringToBigDecimal(roomObj.getString("dspBldArea")));
		room.setDspTnArea(StrUtils.stringToBigDecimal(roomObj.getString("dspTnArea")));
		room.setDspAreaStatusEnum(StrUtils.stringToInteger(roomObj.getString("dspAreaStatusEnum")));
		room.setTradeLocker(roomObj.getString("tradeLocker"));
		room.setTradeLockTime(roomObj.getString("tradeLockTime"));
		room.setBldPrice(StrUtils.stringToBigDecimal(roomObj.getString("bldPrice")));
		room.setIsAreaModify(StrUtils.stringToInteger(roomObj.getString("isAreaModify")));
		room.setTfDate(roomObj.getString("tfDate"));
		room.setIsTfLock(StrUtils.stringToInteger(roomObj.getString("isTfLock")));

		room.setXoffset(StrUtils.stringToInteger(roomObj.getString("Xoffset")));
		room.setYoffset(StrUtils.stringToInteger(roomObj.getString("Yoffset")));

		room.setBaTotal(StrUtils.stringToBigDecimal(roomObj.getString("baTotal")));

		room.setChooseRoom(StrUtils.stringToInteger(roomObj.getString("ChooseRoom")));
		room.setChooseRoomCstName(roomObj.getString("ChooseRoomCstName"));
		room.setChooseRoomLockTime(roomObj.getString("ChooseRoomLockTime"));
		room.setChooseRoomLockEndTime(roomObj.getString("ChooseRoomLockEndTime"));
		room.setChooseRoomGUID(roomObj.getString("ChooseRoomGUID"));
		room.setChooseRoomLockGUID(roomObj.getString("ChooseRoomLockGUID"));
		room.setChooseRoomTime(roomObj.getString("ChooseRoomTime"));

		room.setLsxkTime(roomObj.getString("lsxkTime"));
		room.setJbrGUID(roomObj.getString("jbrGUID"));
		room.setDjShr(roomObj.getString("djShr"));
		room.setDjShdate(roomObj.getString("djShdate"));
		room.setDjShStatus(roomObj.getString("djShStatus"));

		room.setxKingdeesignguid(roomObj.getString("x_KingDeeSignGUID"));
		room.setxSignguid(roomObj.getString("x_SignGUID"));
		room.setIsCarryOver(StrUtils.stringToInteger(roomObj.getString("IsCarryOver")));
		room.setCarryoveredAmounted(StrUtils.stringToBigDecimal(roomObj.getString("CarryoveredAmounted")));
		room.setCarryOverDate(roomObj.getString("CarryOverDate"));
		room.setCarryoverGUID(roomObj.getString("CarryoverGUID"));

		room.setIsDjAreaModify(StrUtils.stringToInteger(roomObj.getString("isDjAreaModify")));
		room.setTimestampId(timestampId);
		room.setIsDeleted(StrUtils.stringToInteger(roomObj.getString("isDeleted")));
		return room;
	}

    public void noticeDownsRecordProcessedInfo(String taskName, String instId, String priceVersionId, String projectId, String stageId, String processedStatus, String processingMode, String source, LocalDateTime now){
        SysNotice notice = new SysNotice();
        notice.setId(UUIDUtils.create());
        notice.setTaskName(taskName);
        notice.setTaskType(ModuleTypeEunm.PRICE.getKey());
        notice.setTaskSource(VersionTypeEunm.DYNAMIC.getKey());
        notice.setProcessingMode(processingMode);
        notice.setReceivingVersionId(instId);
        if(StrUtils.isNotEmpty(source) && source.equals(Constants.MY)){
            notice.setReceivingVersionNo(Constants.MY);
            notice.setAffectedVersionStage(NoticeAffectedEnum.MY_CHANGE.getKey());
        }else if (StrUtils.isNotEmpty(source) && source.equals(Constants.NOS)){
            notice.setReceivingVersionNo(Constants.NOS);
            notice.setAffectedVersionStage(NoticeAffectedEnum.NOS_CHANGE.getKey());
        }else if (StrUtils.isNotEmpty(source) && source.equals(Constants.CLICK)){
            notice.setReceivingVersionNo(Constants.CLICK);
            notice.setAffectedVersionStage(NoticeAffectedEnum.NOS_CHANGE.getKey());
        }else {
            notice.setReceivingVersionNo(Constants.DG);
            notice.setAffectedVersionStage(NoticeAffectedEnum.DG_CHANGE.getKey());
        }
        notice.setAffectedValueVersionId(priceVersionId);
        notice.setProjectId(projectId);
        notice.setStagesId(stageId);
        notice.setState(processedStatus);
        notice.setIsDelete(IsDeleteEnum.NO.getKey());
        notice.setCreateBy(Constants.SYS);
        notice.setCreateTime(now);
        if(processedStatus.equals(ProcessingModeEnum.SYSTEM.getKey())){
            notice.setHandlePerson(Constants.SYS);
            notice.setProcessingTime(now);
        }
        sysNoticeService.save(notice);
    }
    
    /**
     * 根据明源房间刷新货值信息
     */
    class RefreshPriceVersionByMymRooms extends Thread{
    	private LocalDateTime now; 
    	private String instId;
    	private Map<String, String> stageIds;
    	
    	public RefreshPriceVersionByMymRooms(LocalDateTime now,String instId,Map<String, String> stageIds) {
            this.now=now;
            this.instId=instId;
            this.stageIds=stageIds;            
        }
    	
    	public void run() {

          boolean isLocked = synchrolockUtil.islocked(Constants.RedisSyncKey);
          logger.info("====同步锁加锁状态："+isLocked);

          	//TODO 明源签约数据改成ESB下发，上线需修改
            //增量拉取明源签约数据接口
            try{
                dmOdsMyVsMarsSContractServiceImpl.syncIncrement();
            }catch (Exception e){
                logger.error("#########  增量拉取明源签约数据接口  错误信息："+e.getMessage(), e);
            }

            try{
                //归属年月
                LocalDate ascriptionDate = LocalDate.now();
                int day = now.getDayOfMonth();
                int hour = now.getHour();
                if (day == Constants.ONE && hour <=  Constants.SIX){//一号
                    ascriptionDate = ascriptionDate.minusMonths(1);
                }
                //查询货值版本，如果没有动态版本，则不处理，剩余分期直接刷新和生成新版本
                if (CollectionUtils.isNotEmpty(stageIds)) {
                    for (Map.Entry<String, String> stageids : stageIds.entrySet()) {
                        String stageId = stageids.getKey();
                        String timestampId = stageids.getValue();
                        PriceVersion priceVersion = priceVersionServiceImpl.getNewestPriceVersionAllVersionState(stageId);
                        if (priceVersion != null) {
                            String versionType = priceVersion.getVersionType();
                            String versionState = priceVersion.getVersionState();
                            if (versionType.equals(VersionTypeEunm.DYNAMIC.getKey())){
                                if (versionState.equals(VersionStatusEnum.NOTPREPARED.getKey()) || versionState.equals(VersionStatusEnum.ORGANIZATION.getKey())
                                        || versionState.equals(VersionStatusEnum.EXAMINEDAPPROVED.getKey()) || versionState.equals(VersionStatusEnum.FAILUREAPPROVED.getKey())){

                                    Map<String, String> refreshProjectFId = new HashMap<String, String>();
                                    refreshProjectFId.put(stageId, timestampId);

                                    priceVersionValueOrgService.priceRefreshActualValueInfo(stageId, priceVersion, null, null,LocalDateTime.now(), Constants.MY , instId);
                                }else if (versionState.equals(VersionStatusEnum.SUCCESSAPPROVED.getKey())){
                                    try {
                                        String versionId = priceVersionValueOrgService.createSysAppointDynamicVersion(priceVersion.getProjectfId(), priceVersion, null, ascriptionDate, "实际数据刷新生成", 3, instId, Constants.MY);

                                        supplyPlanVersionService.createSupplyPlanVersion(versionId, VersionTypeEunm.DYNAMIC.getKey(), Constants.SYS);
                                    } catch (Exception e) {
                                        logger.error("###################     RefreshPriceVersionByMymRooms    SUCCESSAPPROVED   货值自动生成:"+e.getMessage(), e);
                                    }
                                }else if (versionState.equals(VersionStatusEnum.SYSGENERATION.getKey())){

                                    //查看货值版本是否有被供货确认使用
                                    boolean isComfirm = supplyPlanVersionService.supplyIsComfirm(priceVersion.getId());

                                    if (isComfirm){
                                        try {
                                            String versionId = priceVersionValueOrgService.createSysAppointDynamicVersion(priceVersion.getProjectfId(), priceVersion, null, ascriptionDate, "实际数据刷新生成", 3, instId, Constants.MY);
                                            supplyPlanVersionService.createSupplyPlanVersion(versionId, VersionTypeEunm.DYNAMIC.getKey(), Constants.SYS);
                                        } catch (Exception e) {
                                            logger.error("###################    RefreshPriceVersionByMymRooms  货值自动生成:"+e.getMessage(), e);
                                        }
                                    }else{
                                        //查看货值版本是否有被签约使用
                                        Map<String, Boolean> signMap = signPlanVersionService.priceBoolean(Arrays.asList(priceVersion.getId()));
                                        Boolean isSign = signMap.get(priceVersion.getId());
                                        if (isSign){
                                            try {
                                                String versionId = priceVersionValueOrgService.createSysAppointDynamicVersion(priceVersion.getProjectfId(), priceVersion, null, ascriptionDate, "实际数据刷新生成", 3, instId, Constants.MY);
                                                supplyPlanVersionService.createSupplyPlanVersion(versionId, VersionTypeEunm.DYNAMIC.getKey(), Constants.SYS);
                                            } catch (Exception e) {
                                                logger.error("###################    RefreshPriceVersionByMymRooms   货值自动生成:"+e.getMessage(), e);
                                            }
                                        }else{
                                            //查看货值版本是否有定稿
                                            Integer isFinalization = priceVersion.getIsFinalization();
                                            if (isFinalization != null && isFinalization.equals(IsDeleteEnum.YES.getKey())){
                                                try {
                                                    String versionId = priceVersionValueOrgService.createSysAppointDynamicVersion(priceVersion.getProjectfId(), priceVersion, null, ascriptionDate, "实际数据刷新生成", 3, instId, Constants.MY);
                                                    supplyPlanVersionService.createSupplyPlanVersion(versionId, VersionTypeEunm.DYNAMIC.getKey(), Constants.SYS);
                                                } catch (Exception e) {
                                                    logger.error("###################    RefreshPriceVersionByMymRooms   货值自动生成:"+e.getMessage(), e);
                                                }
                                            }else{
                                                Map<String, String> resultVersionIdAndVersionTypeMap = new HashMap<String, String>();
                                                try{
                                                    resultVersionIdAndVersionTypeMap = priceVersionValueOrgService.priceRefreshActualValueInfo(stageId, priceVersion, null, null,LocalDateTime.now(), Constants.MY , instId);
                                                }catch (Exception e){
                                                    logger.error("###################    RefreshPriceVersionByMymRooms    货值自动生成:"+e.getMessage(), e);
                                                }

                                                if (CollectionUtils.isNotEmpty(resultVersionIdAndVersionTypeMap)){
                                                    for (Map.Entry<String, String> resultmap : resultVersionIdAndVersionTypeMap.entrySet()){
                                                        try {
                                                            supplyPlanVersionService.createSupplyPlanVersion(resultmap.getKey(), resultmap.getValue(), Constants.SYS);
                                                        }catch (Exception e){
                                                            logger.error("###################     RefreshPriceVersionByMymRooms    供货自动生成刷新:"+e.getMessage(), e);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }else if (versionState.equals(VersionStatusEnum.APPROVED.getKey())){
                                    //修改添加代办消息
                                    try{
                                        noticeDownsRecordProcessedInfo(Constants.NOTICE_MY_DELAY, instId, priceVersion.getId(), priceVersion.getProjectId(), priceVersion.getProjectfId(), ProcessingStateEnum.UNTREATED.getKey(), ProcessingModeEnum.SYSTEM_DELAY.getKey(), Constants.MY, now);
                                    }catch (Exception e){
                                        logger.error("################ 添加代办消息 error :"+e.getMessage(), e);
                                    }
                                }
                            }else{
                                if (!versionType.equals(VersionTypeEunm.INVESTMENT.getKey())){
                                    if (versionState.equals(VersionStatusEnum.SUCCESSAPPROVED.getKey())){
                                        try {
                                            String versionId = priceVersionValueOrgService.createSysAppointDynamicVersion(priceVersion.getProjectfId(), priceVersion, null, ascriptionDate, "实际数据刷新生成", 3, instId, Constants.MY);
                                            supplyPlanVersionService.createSupplyPlanVersion(versionId, VersionTypeEunm.DYNAMIC.getKey(), Constants.SYS);
                                        } catch (Exception e) {
                                            logger.error("###################     货值自动生成:"+e.getMessage(), e);
                                        }
                                    }else{
                                        //修改添加代办消息
                                        try{
                                            noticeDownsRecordProcessedInfo(Constants.NOTICE_MY_DELAY, instId, priceVersion.getId(), priceVersion.getProjectId(), priceVersion.getProjectfId(), ProcessingStateEnum.UNTREATED.getKey(), ProcessingModeEnum.SYSTEM_DELAY.getKey(), Constants.MY, now);
                                        }catch (Exception e){
                                            logger.error("################ 添加代办消息 error :"+e.getMessage(), e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }catch (Exception e){
                logger.error("#########  货值变动 错误信息："+e.getMessage(), e);
            }finally {
                synchrolockUtil.unlock(Constants.RedisSyncKey);
                logger.info("====同步锁解锁成功====");
            }
      }
    }
}
